﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace SBToolkit.Utilities
{
    /// <summary>
    /// Maps types with the corresponding interfaces.
    /// </summary>
    public static class TypeMapper
    {
        /// <summary>
        /// Gets the mappings.
        /// </summary>
        /// <param name="type">A <see cref="Type"/> object representing a class in the assembly that will be used.</param>
        /// <param name="namespace">Namespace to narrow search scope for the interfaces.</param>
        /// <param name="exclude">Types that should be excluded from mapping.</param>
        /// <returns>Interface to Class mappings.</returns>
        public static IDictionary<Type, Type> GetMappings(Type type, string @namespace, params Type[] exclude)
        {
            var types = Assembly.GetAssembly(type).GetTypes();

            var pairs = from i in types.Except(exclude)
                        where i.IsInterface && i.FullName.Contains(@namespace)
                        let t = types.FirstOrDefault(x => x.Name == i.Name.Substring(1))
                        where t != null
                        select new KeyValuePair<Type, Type>(i, t);

            return pairs.ToDictionary(p => p.Key, p => p.Value);
        }
    }
}
